package product;

import models.constants.DeletedStatus;
import play.db.jpa.Model;

import javax.persistence.*;
import java.util.Date;
import java.util.List;

/**
 * 产品图片
 * Created by buhaoba on 16/6/14.
 */
@Entity
@Table(name = "product_images")
public class ProductImage extends Model {


    /**
     * 产品详细信息
     */
    @JoinColumn(name = "product_id")
    @ManyToOne
    public Product product;

    /**
     * 产品图片
     */
    @Column(name = "img_path")
    public String imgPath;

    /**
     * 创建时间
     */
    @Column(name = "created_at")
    public Date createdAt;

    /**
     * 逻辑删除,0:未删除，1:已删除
     */
    @Enumerated(EnumType.ORDINAL)
    public DeletedStatus deleted = DeletedStatus.UN_DELETED;

    /**
     * 根据产品ID查询产品图片
     */
    public static List<ProductImage> loadByProductId(long productId){
        return ProductImage.find("product.id = ?1 and deleted = ?2",productId,DeletedStatus.UN_DELETED).fetch();
    }
    public static ProductImage loadFirstByProductId(long productId){
        return ProductImage.find("product.id = ?1 and deleted = ?2",productId,DeletedStatus.UN_DELETED).first();

    }

    /**
     * 删除产品图片
     * @param id
     */
    public static void delProductImg(long id){
        List<ProductImage> list = ProductImage.loadByProductId(id);
        for(ProductImage productImage:list){
            productImage.deleted = DeletedStatus.DELETED;
            productImage.save();
        }

    }

}
